package com.eco.fanliapp.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eco.fanliapp.common.constant.ApiEnum;
import com.eco.fanliapp.common.constant.WechatConfig;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.BannerPictureMapper;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.taobao.SessionController;
import com.eco.fanliapp.vo.BannerPictureVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taobao.api.response.TbkScActivitylinkToolgetResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ProjectName: fanliapp
 * @Package: com.eco.fanliapp.service.impl
 * @ClassName: BannerPictureServiceImpl
 * @Author: LC
 * @Description: 图片信息
 * @Date: 2019/11/28 15:13
 * @Version: 4.2.2
 */
@Service
public class BannerPictureServiceImpl extends ServiceImpl<BannerPictureMapper, BannerPicture> implements IBannerPictureService {

    @Autowired
    private BannerPictureMapper bannerPictureMapper;

    @Autowired
    private IAppUserService appUserService;

    @Autowired
    private IAppCompanyService appCompanyService;

    @Autowired
    private ISyModuleService iSyModuleService;

    @Autowired
    private IGoodsFreeService iGoodsFreeService;
    @Autowired
    private RedisTemplateService redisTemplateService;
    @Autowired
    private IAppUserService iAppUserService;
    @Autowired
    private ITaobaoSchemeService iTaobaoSchemeService;
    @Autowired
    private SessionController sessionController;
    @Autowired
    private IDwzService dwzService;

    /**
     * 动态字段,根据主键来更新符合条件的数据库记录或者增加数据,banner_picture
     *
     * @param bannerPicture
     */
    @Override
    public ServerResponse insertAndUpdate(BannerPicture bannerPicture) {
        String redisModuleKey = "module_list_company====";
        String redisKeyH5 = "app_advertising_h5";
        String redisKeyTrumpet = "app_index_module_trumpet";
        Integer id = bannerPicture.getId();
        // id 不存在，图片第一次添加
        if (id == null) {
            int insert = bannerPictureMapper.insert(bannerPicture);
            if (insert > 0) {
                if(bannerPicture != null && bannerPicture.getPicType() == 5){
                    redisTemplateService.del(redisKeyH5);
                }else if(bannerPicture != null && bannerPicture.getPicType() == 8){
                    redisTemplateService.del(redisKeyTrumpet);
                }else if(bannerPicture != null && (bannerPicture.getPicType() == 8||bannerPicture.getPicType() == 9)){
                    redisTemplateService.del(redisModuleKey);
                }

                return ServerResponse.createBySuccessMessage("图片增加成功");
            } else {
                return ServerResponse.createByErrorMessage("图片增加失败");
            }
        } else {
            int update = bannerPictureMapper.updateById(bannerPicture);
            if (update > 0) {
                if(bannerPicture != null && bannerPicture.getPicType() == 5){
                    redisTemplateService.del(redisKeyH5);
                }else if(bannerPicture != null && bannerPicture.getPicType() == 8){
                    redisTemplateService.del(redisKeyTrumpet);
                }else if(bannerPicture != null && (bannerPicture.getPicType() == 8||bannerPicture.getPicType() == 9)){
                    redisTemplateService.del(redisModuleKey);
                }
                return ServerResponse.createBySuccessMessage("图片修改成功");
            } else {
                return ServerResponse.createByErrorMessage("图片修改失败");
            }
        }
    }

    /**
     * 广告位弹窗和新人免单弹窗互斥
     *
     * @param userId
     * @return
     */
    @Override
    public ServerResponse advertisingPopup(Long userId) {
        String redisKeyAdvertising = "app_advertising_popup_list";
        String redisKeyOnOff = "app_advertising_popup_onoff";
        List<BannerPictureVo> bannerPopupList = null;
        SyModule syModule = null;
        Map map = new HashMap();
        if (redisTemplateService.hasKey(redisKeyAdvertising)) {
            bannerPopupList = redisTemplateService.getTByListKey(redisKeyAdvertising, BannerPictureVo.class);
        }
        if (bannerPopupList == null || bannerPopupList.size() <= 0) {
            bannerPopupList = bannerPictureMapper.bannerModuleList(4, null);
            redisTemplateService.set(redisKeyAdvertising, bannerPopupList, 60 * 5);
        }
        if (redisTemplateService.hasKey(redisKeyOnOff)) {
            syModule = redisTemplateService.getTByKey(redisKeyOnOff, SyModule.class);
        }
        if (syModule == null) {
            syModule = iSyModuleService.getById(6);
            redisTemplateService.set(redisKeyOnOff, syModule, 60 * 5);
        }
        if (syModule != null && syModule.getEnable()) {
            if (bannerPopupList.size() > 0) {
                map.put("popUp", true);
                map.put("onOff", true);
                map.put("list", bannerPopupList);
            }
        } else {
            ServerResponse response = iGoodsFreeService.checkHaveBuy(userId, null);
            if (response.getStatus() == 515) {
                if (bannerPopupList.size() > 0 && bannerPopupList.get(0).getJumpType() == 3) {
                    map.put("popUp", true);
                    map.put("onOff", true);
                    map.put("list", bannerPopupList);
                }
            }

        }
        if (map.size() > 0) {
            return ServerResponse.createBySuccess("获取成功", map);
        } else {
            return ServerResponse.createBySuccess(201, "暂无数据", null);
        }

    }

    /**
     * 首页海报
     *
     * @param userId
     * @return
     */
    @Override
    public ServerResponse homePosterList(Long userId) {
        //app_advertising_h5
        HashMap map = new HashMap();
        List<BannerPictureVo> bannerPopupList = null;

        String redisKeyStr = "app_advertising_h5";
        String activityIdKey = "sy_banner_poster_activityId";
        if (redisTemplateService.hasKey(redisKeyStr)) {
            bannerPopupList = redisTemplateService.getTByListKey(redisKeyStr, BannerPictureVo.class);
        }
        if (bannerPopupList == null) {
            bannerPopupList = bannerPictureMapper.bannerModuleList(5, null);//首页海报5
            redisTemplateService.set(redisKeyStr, bannerPopupList, 60 * 5);
        }
        if (userId == null || !redisTemplateService.hasKey(activityIdKey)) {
            if (bannerPopupList.size() > 0) {
                map.put("list", bannerPopupList);
                return ServerResponse.createBySuccess("数据获取成功", map);
            } else {
                return ServerResponse.createBySuccess(201, "暂无数据", null);
            }
        } else {
            if (bannerPopupList.size() > 0) {
                AppUser appUser = iAppUserService.selectAppUserByUserId(userId, 0);
                TaobaoScheme taobaoScheme = null;
                AppCompany com;

                String generalizePid = "";
                String appSession = "";

                //用户不为空，推广id不为空时，查询用户对应的推广位
                if (appUser != null && appUser.getSchemeId() != null && appUser.getSchemeId() != 0) {
                    taobaoScheme = iTaobaoSchemeService.selectTaobaoSchemeById(appUser.getSchemeId(), 0);
                    if (taobaoScheme != null && taobaoScheme.getGeneralizePid() != null && taobaoScheme.getAppSession() != null) {
                        generalizePid = taobaoScheme.getGeneralizePid();
                        appSession = taobaoScheme.getAppSession();
                    }
                }
                //generalizePid或者appSession 为空时，取公司的值
                boolean isNotHasScheam = (StringUtils.isEmpty(generalizePid) || StringUtils.isEmpty(appSession));

                if (isNotHasScheam) {
                    com = appCompanyService.findtAppCompany(appUser == null ? null : appUser.getCompanyId(), 1);
                    generalizePid = com.getGeneralizePid();
                    appSession = com.getTaoBaoScheme().getAppSession();
                }
                Long siteId = Long.valueOf(generalizePid.split("_")[2]);
                Long adzoneid = Long.valueOf(generalizePid.split("_")[3]);
                Long promotion_sceneid = Long.valueOf(redisTemplateService.getTByKey(activityIdKey,String.class));
                TbkScActivitylinkToolgetResponse response = sessionController.tbkScActivitylinkToolgetResponse(siteId,adzoneid,appSession,appUser.getRelationId().toString(), promotion_sceneid);
                if(response != null &&  response.getData() != null){
                    bannerPopupList.get(0).setPictureLink(response.getData());
                }
                map.put("list", bannerPopupList);
                return ServerResponse.createBySuccess("数据获取成功", map);
            } else {
                return ServerResponse.createBySuccess(201, "暂无数据", null);
            }
        }
    }


    @Override
    public ServerResponse findAll(Integer currentPage, Integer pageSize, Integer companyId) {

        BannerPicture bannerPicture = new BannerPicture();
        bannerPicture.setPictureStatus(2);
        bannerPicture.setDeleted(0);
//        AppCompany appCompany = appCompanyService.selectAppCompanyById(companyId);

//        if (appCompany == null || appCompany.getType() == 1) {
//            companyId = -1;
//        }
        bannerPicture.setCompanyId(companyId);

        List<BannerPicture> bannerPictures = bannerPictureMapper.findAll(bannerPicture);

        return ServerResponse.createBySuccess("数据获取成功", new PageInfo(bannerPictures));
    }

    @Override
    public ServerResponse<PageInfo> findAlls(Integer companyId, Integer currentPage, Integer pageSize) {
        PageHelper.startPage(currentPage, pageSize);
        BannerPicture picture = new BannerPicture();
        picture.setCompanyId(companyId);
        List<BannerPicture> bannerPictures = bannerPictureMapper.findAlls(picture);

        return ServerResponse.createBySuccess("数据获取成功", new PageInfo(bannerPictures));
    }

    @Autowired
    IAppQnyService appQnyService;

    /**
     * 邀请链接-海报生成
     *
     * @param userId
     * @param companyId
     * @return
     */
    @Override
    public ServerResponse<Map<String, Object>> selectByBannerPictureInvitationPoster(
            Long userId, Integer companyId) {
        // TODO Auto-generated method selectByBannerPictureInvitationPoster
        AppQny appQny = appQnyService.getOne();
        if (appQny == null) {
            return ServerResponse.createByErrorMessage("七牛云为空");
        }
        if (userId != null && !"".equals(userId.toString())) {
            AppUser appUser = appUserService.selectAppUserByUserId(userId);
            if (appUser == null) {
                return ServerResponse.createByErrorCodeMessage(505, "请重新登录");
//                return ServerResponse.createByErrorMessage("用户错误");
            }
            String redirectUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + WechatConfig.APPID + "&redirect_uri=" + WechatConfig.RETURNURL + "&response_type=code&scope=snsapi_userinfo&state=share:" + userId + "#wechat_redirect";
            redirectUrl = dwzService.getShorUrl(redirectUrl);
            Map<String, Object> map = new HashMap<>();
            List list = new ArrayList();
            //查询邀请海报
            List<BannerPicture> bannerPictures = bannerPictureMapper.selectByBannerPictureInvitationPoster(companyId);
            for (BannerPicture bannerPicture : bannerPictures) {
                String res = dwzService.createShare1(appQny.getAccesskey(), appQny.getSecretkey(), appQny.getBucket(), appQny.getQnysite(),
                        appUser.getUserName(),
                        appUser.getUserImgUrl(),
                        redirectUrl,
                        bannerPicture.getPictureName(),
                        bannerPicture.getMainPictureUrl());
                if (res != null) {
                    list.add(res);
                }
            }
            map.put("list", list);
            return ServerResponse.createBySuccess("数据获取成功", map);
        } else {
            return ServerResponse.createByErrorMessage("请重新登录");
        }
    }

    /**
     * 邀请赚钱链接-新
     *
     * @param userId
     * @return
     */
    @Override
    public ServerResponse<Map<String, Object>> selectByBannerPictureUrlNew(
            Long userId) {
        // TODO Auto-generated method selectByBannerPictureInvitationPoster

        try {

            AppQny appQny = appQnyService.getOne();
            if (appQny == null) {
                return ServerResponse.createByErrorMessage("七牛云为空");
            }
            if (userId != null && !"".equals(userId.toString())) {
                AppUser appUser = appUserService.selectAppUserByUserId(userId);
                if (appUser == null) {
                    return ServerResponse.createByErrorCodeMessage(505, "请重新登录");
//                return ServerResponse.createByErrorMessage("用户错误");
                }

//                String redirectUrl = ApiEnum.APP_SHARE_URL +"/mobile/home/pages/h5/url" + "?id=" + "" + "&type=5" +
//                        "&invitedCode=" + appUser.getMeInviteCode() +
//                        "&userName=" + URLEncoder.encode(appUser == null ? "" : appUser.getUserName(), "UTF-8") +
//                        "&userUrl=" + URLEncoder.encode(appUser == null ? "" : appUser.getUserImgUrl(), "UTF-8");
//                redirectUrl = dwzService.getShorUrl(redirectUrl);
                String redirectUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + WechatConfig.APPID + "&redirect_uri=" + WechatConfig.RETURNURL + "&response_type=code&scope=snsapi_userinfo&state=share:" + userId + ":" + appUser.getMeInviteCode() + "#wechat_redirect";
                redirectUrl = dwzService.getShorUrl(redirectUrl);
                Map<String, Object> map = new HashMap<>();
                map.put("url", redirectUrl);
                return ServerResponse.createBySuccess("数据获取成功", map);
            } else {
                return ServerResponse.createByErrorMessage("请重新登录");
            }
        } catch (Exception e) {

        }
        return null;
    }

    /**
     * 邀请赚钱链接-旧
     *
     * @param userId
     * @return
     */
    @Override
    public ServerResponse<Map<String, Object>> selectByBannerPictureUrl(
            Long userId) {
        // TODO Auto-generated method selectByBannerPictureInvitationPoster

        try {

            AppQny appQny = appQnyService.getOne();
            if (appQny == null) {
                return ServerResponse.createByErrorMessage("七牛云为空");
            }
            if (userId != null && !"".equals(userId.toString())) {
                AppUser appUser = appUserService.selectAppUserByUserId(userId);
                if (appUser == null) {
                    return ServerResponse.createByErrorCodeMessage(505, "请重新登录");
//                return ServerResponse.createByErrorMessage("用户错误");
                }

                //type=5  邀请赚钱
                //type=0   渠道分享
                //type=1  详情分享

                String redirectUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + WechatConfig.APPID + "&redirect_uri=" + WechatConfig.RETURNURL + "&response_type=code&scope=snsapi_userinfo&state=share:" + userId + "#wechat_redirect";
                redirectUrl = dwzService.getShorUrl(redirectUrl);
                Map<String, Object> map = new HashMap<>();
                map.put("url", redirectUrl);
                return ServerResponse.createBySuccess("数据获取成功", map);
            } else {
                return ServerResponse.createByErrorMessage("请重新登录");
            }
        } catch (Exception e) {

        }
        return null;
    }

    @Override
    public int deleteAll(Integer companyId) {
        return bannerPictureMapper.deleteAll(companyId);
    }

    @Override
    public ServerResponse fakeDelete(Integer id) {
        BannerPicture bannerPicture = new BannerPicture();
        bannerPicture.setId(id);
        bannerPicture.setDeleted(1);
        int bp = bannerPictureMapper.updateById(bannerPicture);
        if (bp > 0) {
            return ServerResponse.createBySuccessMessage("删除成功");
        } else {
            return ServerResponse.createByErrorMessage("删除失败");
        }
    }


}
